<?php

namespace App\Core\Process;

use Illuminate\Console\Command;
use Symfony\Component\Cache\Adapter\FilesystemAdapter;
use Symfony\Component\Process\Process;
use Symfony\Contracts\Cache\ItemInterface;

class DaemonReloadCommand extends Command
{
    protected $signature = 'daemon:reload {pid?}
                            {--signal=-2 : The signal you want send}';

    public function handle()
    {
        $signal = $this->option('signal');
        $fileStorage = new FilesystemAdapter();
        /** @var ItemInterface $pidStorage */
        $pidStorage = $fileStorage->getItem(Daemon::$pidKey);
        $pids = $pidStorage->get();
        echo '准备停止' . implode(',', $pids)."\n";
        foreach ($pids as $k => $pid) {
            echo "kill $signal $pid \n";
            $process = new Process(['kill', $signal, $pid]);
            $process->run();
            echo $process->getOutput();
            if ($process->isSuccessful()) {
                echo "成功 停止 $pid \n";
            }else{
                echo "$pid 异常,请检查 \n";
            }
            unset($pids[$k]);
        }
        $pidStorage->set($pids);
        $fileStorage->save($pidStorage);
    }


}